package com.tank.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.tank.bean.School;
import com.tank.bean.User;
import com.tank.dao.SchoolDAO;
import com.tank.dao.UserDAO;

public class TankUtil {

	public static boolean isLogin(){
		try {
			System.out.println("=isLogin=");
			return null!=ServletActionContext.getRequest().getSession().getAttribute("user");	
		} catch (Exception e) {
			return false;
		}
	}
	
	@SuppressWarnings("finally")
	public static User getCurrentUser(){
		User u = null;
		try {
			u=(User) ServletActionContext.getRequest().getSession().getAttribute("user");
			
		} catch (Exception e) {
			u=new User(1);
			u.setName("zhuoyr");
			u.setPhoto("default.png");
			u.setPass("333");
		}finally{
			//System.out.println("====current:"+u);
			return u;
		}
	}
	
	public static User getUser(Integer id){
		try {
			UserDAO dao=(UserDAO) ApplicationContextUtil.getContext().getBean("userDao");
			System.out.println(dao);
			return dao.findUserById(id);
		} catch (Exception e) {
			return getCurrentUser();
		}
	}
	
	public static void main(String[] args) {
		

	}
	
	public static List<School> getSchools(){
		
		if(schools== null) loadSchool();
		printSchools();
		return schools;
	}
	
	private static void printSchools() {
//		String[][]={
//				{							<option value="0">=请选择=</option>
//				<option value="1">福建农林大学</option>
//				<option value="2">福州大学</option>
//				<option value="3">福建医科大学</option>}
//		}
		
		
		
//		System.out.println(schools);
//		if(schools.size()<10){
//			loadSchool();
//		}
		for(School s:schools){
			System.out.println(s.getId()+":"+s.getName());
		}
	}

	private static List<School> schools;

	private static void loadSchool() {
		SchoolDAO dao=(SchoolDAO) ApplicationContextUtil.getContext().getBean("schoolDao");
		try {
			
			schools=dao.findAll();
			if(schools.size()<1) initSchools(dao);
			
		} catch (Exception e) {
//			schools=new ArrayList<School>();
//			School s=new School();
//			s.setName("==请添加学校==");
//			s.setOther("<>");
//			schools.add(s);

			if(schools==null ){
				initSchools(dao);
			}
			
		}
		
	}

	private static void initSchools(SchoolDAO dao) {
		schools=new ArrayList<School>();
		schools.add(new School(1,"=请选择="));
		schools.add(new School(2,"福建农林大学"));
		schools.add(new School(3,"福州大学"));
		schools.add(new School(4,"福建医科大学"));
		for(School s:schools){
			dao.save(s);
		}
		
	}

}
